<?php
 /***************************************************************
 * Mor-MVC Framework, A framework that can easily let you build a powerful
 * and scalable web application based on PHP language,
 * this framewrok is a copy of the Zend Behavior Framework
 *  Copyright (C) 2010  Nabil Droussi <nabildroussi@gmail.com>
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ***************************************************************/
require_once("DataAccess.php");

class CommandExecutor extends DataAccess
{
    public function __construct()
    {
        $this->_adapter = DBAdapter::getInstance()->getDBInterface();
        $this->getSchema();
    }
    public function insert()
    {
        
        $fields = implode(",",$this->getFieldsTable());
        $values = implode(",",$this->getObjectValues());
        $req = "insert into `{$this->_name}`({$fields}) values({$values})";
        $returnValue = $this->executeQuery($req);
        if($returnValue>0)
        {
            $this->{$this->getPrimaryKeyField()} = mysql_insert_id($this->getAdapter()->getResource());
        }
        return $returnValue;
    }
    public function update()
    {
        $keyField = $this->getPrimaryKeyField();
        if(!isset($keyField))
            throw new Exception("Object is not valid for update");
        $query = "update `{$this->_name}` set ";
        $fields = $this->getFieldsTable();
        $values = $this->getObjectValues();
        $i=0;
        foreach($fields as $value)
        {
            $i++;
            if($value != $this->getPrimaryKeyField())
            {
                $query .= sprintf("`%s`='%s'",$value,$this->{$value});
                if($i != count($fields))
                   $query .= ", ";
            }
        }
        $query .= sprintf(" where `%s`='%s'",$this->getPrimaryKeyField(),$this->{$this->getPrimaryKeyField()});
        return $this->executeQuery($query);
    }
    public function delete($where=NULL)
    {
        $keyField = $this->{$this->getPrimaryKeyField()};
        $query = sprintf("delete from `%s`",$this->_name);
        if(isset($where) && !empty($where))
            $query .= " where ".$where;
        elseif(isset($keyField) && isset($keyField))
       {
            $query .= " where `".$this->getPrimaryKeyField()."`='".$this->{$this->getPrimaryKeyField()}."'";
       }
       return $this->executeQuery($query);
    }
    public function selectRaw($query,$where=null,$group=null, $order=null, $limit=null, $stack=null)
    {
        if(isset($where))
        {
            $query .= " where ".$where;
        }
        if(isset($group))
            $query .= " group by ".$group;
        
        if(isset($order))
            $query .= " order by ".$order;

        if(isset($limit) && !isset($stack))
            $query .= " limit %s".$limit;
        elseif(isset($limit) && isset($stack))
            $query .= sprintf(" limit %s, %s",$stack,$limit);
         
        $res = $this->executeQuery($query);
        $numOfRows = mysql_num_rows($res->result);
        
        if($numOfRows == 0)
            return NULL;
        
        elseif($numOfRows == 1)
        {
            $tmpRow = $res->fetchRow();
            $thisObject = clone $this;
            $this->bindData($tmpRow,$thisObject);
            return array($thisObject);
        }else
        {
            $objectsList = array();
            while($row = $res->fetchRow())
            {
                $tmpObj = clone $this;
                $this->bindData($row,$tmpObj);
                $objectsList[] = $tmpObj;
            }
            return $objectsList;
        }
    }
    public function select($where=null,$group=null, $order=null, $limit=null, $stack=null)
    {
        $query = "select * from `{$this->_name}`";
        return $this->selectRaw($query,$where,$group,$order,$limit,$stack);
    }
    public function selectJoin($fields,$tables,$where=null,$order=null,$group=null,$limit=null,$stack=null)
    {
        if(is_array($fields))
            $fields = implode(",", $fields);
        $query = sprintf("select %s from %s",$fields,$this->_name);
        foreach($tables as $table)
        {
           $query .= sprintf(" %s %s on %s",$table[0],$table[1],$table[2]);
        }
        return $this->selectRaw($query,$where,$order,$group,$limit,$stack);
    }
    
    private function bindData($sourceObject,$destinationObject)
    {
        $objectAttributes = get_object_vars($sourceObject);
        $objectAttributes = array_keys($objectAttributes);
        foreach($objectAttributes as $field)
        {
            $destinationObject->{$field} = $sourceObject->{$field};
        }
    }
    public function find()
    {
        
    }
    private function getObjectValues()
    {
        $values = array();
        foreach($this->getFieldsTable() as $value)
        {
            $values[] = "'".$this->{$value}."'";
        }
        return $values;
    }
}